package cn.edu.tju.se.auth.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.edu.tju.se.auth.repository.RoleRepository;
import cn.edu.tju.se.auth.enity.Privilege;
import cn.edu.tju.se.auth.enity.Role;
import cn.edu.tju.se.auth.enity.Udr;
import cn.edu.tju.se.auth.service.PrivilegeService;
import cn.edu.tju.se.auth.service.RoleService;
import cn.edu.tju.se.auth.service.UdrService;

@Service
public class RoleServiceImpl implements RoleService{

	@Autowired RoleRepository roleRepository;
	@Autowired UdrService tjqsUdrService;
	@Autowired PrivilegeService tjqsPrivilegeService;
	@Override
	public boolean hasPriv(Role role, String Priv) {
		Set<Privilege> myPriv=role.getPrivileges();
		for(Privilege priv:myPriv){
			if(priv.getName().equalsIgnoreCase(Priv))
				return true;
		}
		return false;
	}

	@Override
	public Role get(Long id) {
		return roleRepository.findOne(id);
	}

	@Override
	public List<Role> getAll() {
		return roleRepository.findAll();
	}

	@Override
	public Role save(Role role) {
		Set<Privilege> myPriv=new HashSet<Privilege>();
		role.setPrivileges(myPriv);
		Set<Udr> myUdr=new HashSet<Udr>();
		role.setMyUdr(myUdr);
		return roleRepository.save(role);
	}

	@Override
	public void update(Role role) {
		Role r=this.get(role.getId());
		role.setMyUdr(r.getMyUdr());
		roleRepository.save(role);
	}

	@Override
	public void delete(Long id) {
		Role r=this.get(id);
		tjqsUdrService.deleteAll(r.getMyUdr(),"role");
		r.setPrivileges(new HashSet<Privilege>());
		roleRepository.delete(id);
	}

}
